package com.csw.android.localplayer.ui.local

import android.net.Uri
import android.provider.MediaStore
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.csw.android.dev_utils.SDK
import com.csw.android.dev_utils.utils.ToastUtils
import com.csw.android.localplayer.R
import com.csw.android.player.base.MediaInfo
import kotlinx.coroutines.*

class LocalViewModel : ViewModel() {

    val localMediaItems = MutableLiveData<ArrayList<MediaInfo>?>()

    fun getLocalMedia() = viewModelScope.launch {
        localMediaItems.postValue(
            try {
                getLocalVideos()
            } catch (e: Exception) {
                e.printStackTrace()
                if (e !is CancellationException) {
                    ToastUtils.showShort(R.string.app_error_local_media_scan_failed)
                }
                null
            }
        )
    }

    /**
     * 查询设备媒体库获取所有视频文件数据记录，数据量大的时候耗时较长
     */
    private suspend fun getLocalVideos() = withContext(Dispatchers.IO) {
        val data = arrayListOf<MediaInfo>()
        SDK.getApplication().contentResolver.query(
            MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            null,//要查询的列，null所有列
            null,//筛选条件（用占位符代替参数值）
            null,//筛选参数
            MediaStore.Video.Media.DATE_MODIFIED + " DESC "//按数据修改日期反向排序
        )?.use {
            val idIndex = it.getColumnIndex(MediaStore.Video.Media._ID)
            var mediaDbId: Long
            var uri: String
            if (idIndex >= 0 && it.moveToFirst()) {
                do {
                    mediaDbId = it.getLong(idIndex)
                    if (mediaDbId != 0L) {
                        uri = "${MediaStore.Video.Media.EXTERNAL_CONTENT_URI}/${mediaDbId}"
                        data.add(MediaInfo(uri, Uri.parse(uri), Uri.parse(uri)))
                    }
                } while (it.moveToNext() && isActive)
            }
        }
        data
    }
}